<?php
namespace Home\Controller;

class CartController extends BaseController
{
    //添加到购物车
    public function add_cart()
    {
       if(empty($_SESSION['user_id']) ){
            //要回调的url
            $this->ajaxReturnData(array('url' => U('Public/login')), 0, '请登录');
        }
        
        if ($_SESSION['form'] !== $_POST['form']) {
            $this->ajaxReturnData(null, 0, '恶意攻击将负法律责任');
        }
        
        //监测传值
       \Common\Tool\Tool::checkPost($_POST, array(
            'is_numeric' => array('fanli_jifen', 'goods_id', 'goods_num', 'price_new'),'taocan_name'
        ), true, array('goods_id', 'goods_num', 'price_new')) === false ? $this->ajaxReturnData(null, 0, '数据有误') : true;
        
       $model = new \Home\Model\GoodsCartModel();
       
       $isSucess = $model->addCart($_POST);
       
       $status  = $isSucess === true ? 1 : 0;
       $message = $isSucess === true ? '添加成功' : '添加失败';

       $this->ajaxReturnData(null, $status, $message);
    }



    //购物车列表
/*    public function goods_cart(){
            if(empty($_SESSION['user_id']) || empty($_SESSION['mobile'])){
                $this->redirect('Public/login');
            }
            $m = M('goods_cart');
            $where['user_id'] = $_SESSION['user_id'];
            $result = $m->field('shoper_id')->where($where)->group('shoper_id')->select();
            $shoper = M('shoper');
            $g = M('Goods');
            foreach ($result as $k=>$v){
                $shoper_id['id'] = $v['shoper_id'];
                $shoper_name = $shoper->field('shoper_name')->where($shoper_id)->find();
                $result[$k]['shoper_name'] = $shoper_name['shoper_name'];
                $where_sub['shoper_id'] = $v['shoper_id'];
                $result[$k]['goods_sub'] = $m->where($where_sub)->select();
            }
            $count = count($result);
            $this->assign('count',$count);
            $this->assign('result',$result);
            
            $m = M('foot_print');
            $where_zuji['uid'] = $_SESSION['user_id'];
            $result_zuji = $m->where($where_zuji)->limit('5')->select();
            $this->assign('result_zuji',$result_zuji);
            
            $m = M('goods_shoucang');
            $where_shoucang['user_id'] = $_SESSION['user_id'];
            $result_shoucang = $m->where($where_shoucang)->limit('5')->select();
            $this->assign('result_shoucang',$result_shoucang);           
            $this->display();
    }*/




    //购物车列表
    public function goods_cart(){
            if(empty($_SESSION['user_id']) || empty($_SESSION['mobile'])){
                $this->redirect('Public/login');
            }
            $m = M('goods_cart');
            $where['user_id'] = $_SESSION['user_id'];
            $result = $m->where($where)->select();
            
            $g = M('Goods');
            $shoper = M('shoper');
            foreach ($result as $k=>$v){
                $where_1['id'] = $v['goods_id'];
                $res_price = $g->field('title,price_new,pic_url,taocan')->where($where_1)->find();
                $result[$k]['price_sum'] = $res_price['price_new'] * $v['goods_num'];
				$result[$k]['goods_title'] = $res_price['title'];
				$result[$k]['pic_url'] = $res_price['pic_url'];

                $shoper_id['id'] = $v['shoper_id'];
                $shoper_name = $shoper->field('shoper_name')->where($shoper_id)->find();
                $result[$k]['shoper_name'] = $shoper_name['shoper_name'];
            }
            
            $_SESSION['form'] =  base64_encode(md5(C('form').$_SERVER['user_id']));
            
            $count = count($result);
            $this->assign('count',$count);
            $this->assign('result',$result);
			$m = M('foot_print');
			$where_zuji['uid'] = $_SESSION['user_id'];
			$result_zuji = $m->where($where_zuji)->limit('5')->select();
			$this->assign('result_zuji',$result_zuji);
			
			$m = M('goods_shoucang');
			$where_shoucang['user_id'] = $_SESSION['user_id'];
			$result_shoucang = $m->where($where_shoucang)->limit('5')->select();
			$this->assign('result_shoucang',$result_shoucang);
			
			
            $this->display();

    }

    //更新购物车商品的数量
    public function update_goods_num(){
        $m = M('goods_cart');
        $where['id'] = $_GET['id'];
        $result = $m->where($where)->save($_GET);
        if($result){
            $this->ajaxReturn(1);
        }else {
            $this->ajaxReturn(0);
        }
    }
    //删除购物车里面的商品
    public function cart_del(){
        $m = M('goods_cart');
        $where['id'] = $_GET['id'];
        $result = $m->where($where)->delete();
        if($result){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }

    }

    //删除购物车里面的多个商品
    public function cart_mony_del(){
        $m = M('goods_cart');
        $id = $_POST['id'];
        $result = $m->delete($id);
        if(!$result){
            $data['code'] = 0;
            $this->ajaxReturn($data);
        }else{
            $data['code'] = 1;
            $data['id'] = $id;
            $this->ajaxReturn($data);
        }
    }
    
    /**
     * 订单前操作 
     */
    public function before_order()
    {
        //验证是否登录
        if( empty($_SESSION['user_id']) ) {
            $this->redirect('Public/login');
        }
        
        
        //检测传值
        \Common\Tool\Tool::checkPost($_POST, array(
            'is_numeric' => array('goods_id', 'goods_num')
        ), true, array(
            'goods_id', 'goods_num', 'form'
        )) === false ? $this->error('灌水机制已经打开') : true;
        
        if ($_SESSION['form'] !== $_POST['form']) {
            $this->error('恶意攻击将追究法律责任');
        }
      
        // 查询商品信息
        
        $goods_model = new \Home\Model\GoodsModel();
        
        $where = is_array($_POST['goods_id']) ? array('id' => array('in', implode(',', $_POST['goods_id']))) : array('id' => $_POST['goods_id']);
        
        $goods_data  = $goods_model->getGoods(array(
            'where' => $where,
            'field' => array('id,title,price_new,pic_url,fanli_jifen,taocan,min_yunfei,min_yunfei,max_yunfei,add_yunfei,chufa_address,chufa_date')
        ), $_POST['goods_num']);
        
       //获取 当前登录用户信息
        $address_model = new \Home\Model\UserAddressModel();
        
        $address_data   = $address_model->getUserAddressInfo(array(
            'where' => array('user_id' => $_SESSION['user_id']),
            'field' => array('id,status,realname,mobile,prov,city,dist,address'),
        ));
        
        //获取默认地址
        $address_default = $address_model->getDefaultAddress($_SESSION['user_id']);
        //获取运费计算的相关信息
        $freight = new \Home\Model\FreightModel();
        
        $freight_info = $freight->getFreight(array(
            'where' => array('name' => $address_default['res_ad']['prov']),
            'field' => array('areaid')
        ), new \Think\Model('region'));
        //计算运费
        $sum_freight = $goods_model->countFreight($goods_data, $address_default['res_ad']['prov'],$freight_info);
        
        //查询用户积分
        $user_model = new \Home\Model\UserModel();
        
        $integral   = $user_model->getIntegral($_SESSION['user_id']);
        $goods_info = array('count_goods' => count($_POST['goods_num']), 'zong' => $goods_data['total_monery']);
        
        //订单号生成
        $_SESSION['orders_number'] = time().sprintf("%06s",$_SESSION['user_id']);
        
        $this->res_addr    = $address_data;
        $this->list        = $goods_data;
        //商品数量
        $this->goods_info = $goods_info;
        //默认地址
        $this->res_ad     = $address_default;   
        //商品总金额
        $this->price_sum  = $goods_data['total_monery'] + $sum_freight;
        //积分
        $this->integral   = $integral;
        $this->display();
    }
        
//     //订单前操作
    public function before_order123(){

		if($_SESSION['user_id']==''){
            $this->redirect('Public/login');
        }
        foreach ($_POST['checkbox'] as $key => $val) {
				$arr['id'][] = $_POST['id'][$val];  //购物车ID
				$arr['pic_url'][] = $_POST['pic_url'][$val];
				$arr['goods_title'][] = $_POST['goods_title'][$val];
				$arr['fanli_jifen'][] = $_POST['fanli_jifen'][$val];
				$arr['taocan_name'][] = $_POST['taocan_name'][$val];
				$arr['price_new'][] = $_POST['price_new'][$val];

				$arr['goods_num'][] = $_POST['goods_num'][$val];
                $arr['goods_num_et'] = $_POST['goods_num_et'][$val];

                $arr['chufa_price'] = $_POST['chufa_price'][$val]; 
                $arr['chufa_price_et'] = $_POST['chufa_price_et'][$val]; 
		}

		$arr['price_sum'] = $_POST['price_sum'];
        //获得传递过来的数据 并且做相关的处理
        if(!empty($_POST)){
            $data = array();
            if($_POST['now_buy'] == 1){		//判断是否是立即支付
            	$_SESSION['dingdan_order']  = $_POST;
            	$data['dingdan_order'] = $_POST;
            }else{
            	$_SESSION['dingdan_order']  = $arr;
            	$data['dingdan_order'] = $arr;
            }           
            $_SESSION['user_id'] = $_SESSION['user_id'];
            $_SESSION['orders_number'] = time().sprintf("%06s",$_SESSION['user_id']);
            
            $data['user_id'] = $_SESSION['user_id'];
            $data['orders_num'] = $_SESSION['orders_number'];
        }else{
            $data = array();
            $data['dingdan_order'] = session('dingdan_order');
            $data['user_id'] = session('user_id');
            $data['orders_num'] = session('orders_number');
        }


        $count_goods =  count($data['dingdan_order']['id']);
        //总的花费的价格
        $price_sum = $data['dingdan_order']['price_sum'];
        //将总的价格去处
        unset($data['dingdan_order']['price_sum']);
        $data_a = array();
        if(isset($data['dingdan_order']['chufa_date'])){
            foreach($data['dingdan_order']['id'] as $k=>$v){
                $data_a[$k]['id'] = $data['dingdan_order']['id'][$k];
                $data_a[$k]['pic_url'] = $data['dingdan_order']['pic_url'][$k];

                $data_a[$k]['goods_num'] = $data['dingdan_order']['goods_num'][$k];
                $data_a[$k]['goods_num_et'] = $data['dingdan_order']['goods_num_et'][$k];

                $data_a[$k]['price_new'] = $data['dingdan_order']['price_new'][$k];
                $data_a[$k]['goods_title'] = $data['dingdan_order']['goods_title'][$k];
                $data_a[$k]['chufa_date'] = $data['dingdan_order']['chufa_date'][$k];
                $data_a[$k]['chufa_address'] = $data['dingdan_order']['chufa_address'][$k];	
                $data_a[$k]['fanli_jifen'] = $data['dingdan_order']['fanli_jifen'][$k];	

                $data_a[$k]['chufa_price'] = $data['dingdan_order']['chufa_price'][$k]; 
                $data_a[$k]['chufa_price_et'] = $data['dingdan_order']['chufa_price_et'][$k]; 	
            }
        }else{
            foreach($data['dingdan_order']['id'] as $k=>$v){
                $data_a[$k]['id'] = $data['dingdan_order']['id'][$k];
                $data_a[$k]['pic_url'] = $data['dingdan_order']['pic_url'][$k];

                $data_a[$k]['goods_num'] = $data['dingdan_order']['goods_num'][$k];
                $data_a[$k]['goods_num_et'] = $data['dingdan_order']['goods_num_et'][$k];

                $data_a[$k]['price_new'] = $data['dingdan_order']['price_new'][$k];
                $data_a[$k]['goods_title'] = $data['dingdan_order']['goods_title'][$k];
                $data_a[$k]['fanli_jifen'] = $data['dingdan_order']['fanli_jifen'][$k];
                $data_a[$k]['taocan_name'] = $data['dingdan_order']['taocan_name'][$k];

                $data_a[$k]['chufa_price'] = $data['dingdan_order']['chufa_price'][$k]; 
                $data_a[$k]['chufa_price_et'] = $data['dingdan_order']['chufa_price_et'][$k];                 
            }

        }
		//dump($data_a);
		
        $user_address = M('User_address');
        $map =array();
        $map['user_id']= $_SESSION['user_id'];
        $map['status']= 1;
        $count = $user_address->field('id')->where($map)->count();
        $res_addr_alone = $user_address->where($map)->find();
		if(empty($res_addr_alone)){
			$res_addr_alone = $user_address->where("user_id = {$map['user_id']}")->order('create_time')->find();
		}
        if(!empty($res_addr_alone)){

            $addr_alone = $res_addr_alone['prov'].$res_addr_alone['city'].$res_addr_alone['dist'].$res_addr_alone['address'];
            $res_addr_alone['addr_alone'] = $addr_alone;
            //默认的
            $this->assign('res_ad',$res_addr_alone);
        }
		//邮费
		//dump($data_a);
		//dump($res_addr_alone);exit;
		$youfei=$this->count_freight($data_a,$res_addr_alone["prov"]);
		//dump($youfei);
		
		$this->assign('youfei',$youfei);
        //显示出商家的地址

        $where =array();
        $where['user_id']= $_SESSION['user_id'];
        $res_addr = $user_address->field('id,status,realname,mobile,prov,city,dist,address')->where($where)->select();
		if($_POST['order_type']==0 || $_POST['order_type']==1){
			//查询账户积分余额
		  $member=M('user');
		  $my=M('user')->where(array('id'=>$_SESSION['user_id']))->field('add_jf_currency,add_jf_limit')->find();
			
		}
		//dump($_POST['type']);     
        //订单类型  0 商品   1 旅游   2 会员   3 事业合伙人
        $this->assign('order_type',$_POST['type']);

        //实际消费的价格
		$price_sum = $price_sum + $youfei;

        $this->assign('price_sum',$price_sum);
		//节省金额
		$this->assign('free',$free);
		//分配抵扣积分
// 		$this->assign('jf_a',$jf_a);
// 		$this->assign('jf_b',$jf_b);
		
		$this->assign('jfa',$my['add_jf_limit']);
		$this->assign('jfb',$my['add_jf_currency']);
		/**查询用户等级**/
			$grade=M('member','vip_')->where(array('id'=>$_SESSION['user_id']))->getField('grade_name');
			$this->assign('grade',$grade);
		//商品总金额
		$this->assign('zong',$price_sum);
        //有默认地址
        $this->assign('count',$count);
        //填写右击地址的总数
        $this->assign('res_addr',$res_addr);
        //准备购买的商品的总数
        $this->assign('list',$data_a);

        //总的商品的个数
        $this->assign('count_goods',$count_goods);


        $this->display();
    }
	
    //旅游的
    public function before_order_lvyou(){

        if($_SESSION['user_id']==''){
            $this->redirect('Public/login');
        }
        foreach ($_POST['checkbox'] as $key => $val) {
                $arr['id'][] = $_POST['id'][$val];  //购物车ID
                $arr['pic_url'][] = $_POST['pic_url'][$val];
                $arr['goods_title'][] = $_POST['goods_title'][$val];
                $arr['fanli_jifen'][] = $_POST['fanli_jifen'][$val];
                $arr['taocan_name'][] = $_POST['taocan_name'][$val];
                $arr['price_new'][] = $_POST['price_new'][$val];

                $arr['goods_num'][] = $_POST['goods_num'][$val];
                $arr['goods_num_et'] = $_POST['goods_num_et'][$val];

                $arr['chufa_price'] = $_POST['chufa_price'][$val]; 
                $arr['chufa_price_et'] = $_POST['chufa_price_et'][$val]; 
        }

        $arr['price_sum'] = $_POST['chufa_price'][0] * $_POST['goods_num'][0] + $_POST['chufa_price_et'][0] * $_POST['goods_num_et'][0];


        //获得传递过来的数据 并且做相关的处理
        if(!empty($_POST)){
            $data = array();
            if($_POST['now_buy'] == 1){     //判断是否是立即支付
                $_SESSION['dingdan_order']  = $_POST;
                $data['dingdan_order'] = $_POST;
            }else{
                $_SESSION['dingdan_order']  = $arr;
                $data['dingdan_order'] = $arr;
            }           
            $_SESSION['user_id'] = $_SESSION['user_id'];
            $_SESSION['orders_number'] = time().sprintf("%06s",$_SESSION['user_id']);
            
            $data['user_id'] = $_SESSION['user_id'];
            $data['orders_num'] = $_SESSION['orders_number'];
        }else{
            $data = array();
            $data['dingdan_order'] = session('dingdan_order');
            $data['user_id'] = session('user_id');
            $data['orders_num'] = session('orders_number');
        }

        //总的花费的价格
        $price_sum = $_POST['chufa_price'][0] * $_POST['goods_num'][0] + $_POST['chufa_price_et'][0] * $_POST['goods_num_et'][0];
        $this->assign('price_sum',$price_sum);


        //将总的价格去处
        unset($data['dingdan_order']['price_sum']);
        $data_a = array();
        if(isset($data['dingdan_order']['chufa_date'])){
            foreach($data['dingdan_order']['id'] as $k=>$v){
                $data_a[$k]['id'] = $data['dingdan_order']['id'][$k];
                $data_a[$k]['pic_url'] = $data['dingdan_order']['pic_url'][$k];

                $data_a[$k]['goods_num'] = $data['dingdan_order']['goods_num'][$k];
                $data_a[$k]['goods_num_et'] = $data['dingdan_order']['goods_num_et'][$k];

                $data_a[$k]['price_new'] = $data['dingdan_order']['price_new'][$k];
                $data_a[$k]['goods_title'] = $data['dingdan_order']['goods_title'][$k];
                $data_a[$k]['chufa_date'] = $data['dingdan_order']['chufa_date'][$k];
                $data_a[$k]['chufa_address'] = $data['dingdan_order']['chufa_address'][$k]; 
                $data_a[$k]['fanli_jifen'] = $data['dingdan_order']['fanli_jifen'][$k]; 

                $data_a[$k]['chufa_price'] = $data['dingdan_order']['chufa_price'][$k]; 
                $data_a[$k]['chufa_price_et'] = $data['dingdan_order']['chufa_price_et'][$k];   
            }
        }else{
            foreach($data['dingdan_order']['id'] as $k=>$v){
                $data_a[$k]['id'] = $data['dingdan_order']['id'][$k];
                $data_a[$k]['pic_url'] = $data['dingdan_order']['pic_url'][$k];

                $data_a[$k]['goods_num'] = $data['dingdan_order']['goods_num'][$k];
                $data_a[$k]['goods_num_et'] = $data['dingdan_order']['goods_num_et'][$k];

                $data_a[$k]['price_new'] = $data['dingdan_order']['price_new'][$k];
                $data_a[$k]['goods_title'] = $data['dingdan_order']['goods_title'][$k];
                $data_a[$k]['fanli_jifen'] = $data['dingdan_order']['fanli_jifen'][$k];
                $data_a[$k]['taocan_name'] = $data['dingdan_order']['taocan_name'][$k];

                $data_a[$k]['chufa_price'] = $data['dingdan_order']['chufa_price'][$k]; 
                $data_a[$k]['chufa_price_et'] = $data['dingdan_order']['chufa_price_et'][$k];                 
            }

        }
        //dump($data_a);
        
        $user_address = M('User_address');
        $map =array();
        $map['user_id']= $_SESSION['user_id'];
        $map['status']= 1;
        $count = $user_address->field('id')->where($map)->count();
        $res_addr_alone = $user_address->where($map)->find();
        $this->assign('res_addr_alone',$res_addr_alone);

        $where =array();
        $where['user_id']= $_SESSION['user_id'];
        $res_addr = $user_address->field('id,status,realname,mobile,prov,city,dist,address')->where($where)->select();
        if($_POST['order_type']==0 || $_POST['order_type']==1){
            //查询账户积分余额
          $member=M('user');
          $my=M('user')->where(array('id'=>$_SESSION['user_id']))->field('add_jf_currency,add_jf_limit')->find();
            
        }
        //dump($_POST['type']);     
        //订单类型  0 商品   1 旅游   2 会员   3 事业合伙人
        $this->assign('order_type',$_POST['type']);

        //实际消费的价格
        $price_sum = $price_sum + $youfei;

        $this->assign('price_sum',$price_sum);
        //节省金额
        $this->assign('free',$free);
        //分配抵扣积分
        //$this->assign('jf_a',$jf_a);
        //$this->assign('jf_b',$jf_b);
        
        $this->assign('jfa',$my['add_jf_limit']);
        $this->assign('jfb',$my['add_jf_currency']);
        /**查询用户等级**/
            $grade=M('member','vip_')->where(array('id'=>$_SESSION['user_id']))->getField('grade_name');
            $this->assign('grade',$grade);
        //商品总金额
        $this->assign('zong',$price_sum);
        //有默认地址
        $this->assign('count',$count);
        //填写右击地址的总数
        $this->assign('res_addr',$res_addr);
        //准备购买的商品的总数
        $this->assign('list',$data_a);

        //总的商品的个数
        $this->assign('count_goods',$count_goods);


        $this->display();
    }
	
    //增加新地址
    public function addr_add(){
        if(!empty($_POST)){
            $user_address = M('User_address');
            if($_POST['status']==1){
                $user_id = $_POST['user_id'];
                $res_a = $user_address->field('status,id')->where('user_id='.$user_id)->select();
                foreach($res_a as $k=>$v){
                    if($v['status']==1){
                        $id = $v['id'];
                        $user_address->where('id='.$id)->setField('status',0);
                    }
                }
            }
            $info = $user_address->add($_POST);
            if(!$info){
                $this->ajaxReturn(0);
            }else{
                $this->ajaxReturn(1);
            }
        }else{
            $user_id = $_SESSION['user_id'];
            $this->assign('user_id',$user_id);
            $this->display();
        }

    }

    //地址编辑
    public  function addr_edite(){
        $user_address = M('User_address');
        $id = I('get.id');
        if(!empty($_POST)){
            $id = I('post.id');
            $update_time = time();
            $user_id = $_SESSION['user_id'];
            $status = I('post.status');
            if($status==1){
                $res = $user_address->field('id')->where('user_id='.$user_id)->select();
                foreach($res as $k=>$v){
                    $id = $v['id'];//地址的主键id
                    $user_address->where('id='.$id)->setField('status',0);
                }
            }

            $info = $user_address->where('id='.$id)->save(array(
                    'realname'=>I('post.realname'),
                    'address'=>I('post.address'),
                    'mobile'=>I('post.mobile'),
                    'prov'=>I('post.prov'),
                    'city'=>I('post.city'),
                    'dist'=>I('post.dist'),
                    'status'=>I('post.status'),
                    'update_time' =>$update_time,
            ));
            if(!$info){
                $this->ajaxReturn(0);
            }else{
                $this->ajaxReturn(1);
            }
        }else{
            $res = $user_address->where('id='.$id)->find();
            $this->assign('res',$res);
            $this->display();
        }
    }


  
     //形成订单
    public function order_form(){
        $data =array();
		$usermodel=M('user');
		$my=$usermodel->where(array('id'=>session('user_id')))->find();

		$jfa=I('post.jfa');
		$jfa=floatval($jfa);
		$jfb=I('post.jfb');
		$yunfei=I('post.yunfei');
		//dump($yunfei);
		//exit;
		$jfb=floatval($jfb);
		if($jfa<0 || $jfb<0){
			$this->error('积分不能为负数');
			exit;
		}
		if($my['grade_name']=="合伙人"){
			//合伙人不能用积分购买旅游产品
			if(I('post.order_type')==1){
				$data['use_jf_limit']=0;
				$data['use_jf_currency']=0;
			}else{
				//合伙人只判断B账户
				if($jfb>$my['add_jf_currency']){
				    $this->error('积分账户不足'.$jfb);
				}else{
					$data['use_jf_limit']=0;
					$data['use_jf_currency']=$jfb;
				}
			}
			
        }else{
			if(I('post.order_type')==1){//会员购买旅游产品
				$data['use_jf_limit']=0;
				if($jfb>$my['add_jf_currency']){
				    $this->error('积分B账户不足'.$jfb);
				}else{
					$data['use_jf_currency']=$jfb;
				}
			}else{                       //会员网购
				//会员两个账户都要判断
				if($jfa>$my['add_jf_limit']){
				$this->error('积分A账户不足'.$jfa);
				exit;
				}
				if($jfb>$my['add_jf_currency']){
				$this->error('积分B账户不足'.$jfb);
				exit;
				}
				$data['use_jf_limit']=$jfa;
				$data['use_jf_currency']=$jfb;
			}
		}
		if($jfa+$jfb>I('post.price_sum')){
			$this->error('亲,你花费的积分超过了商品总额了哦!');
		}



        $data['user_id'] = session('user_id');
        $data['user_address'] = I('post.user_address');
        $data['realname'] = I('post.realname');
        $data['mobile'] = I('post.mobile');
        $data['orders_num'] = session('orders_number');

        $goods_orders = M('Goods_orders');
        $data['price_sum'] = I('post.price_sum')-($data['use_jf_currency']+$data['use_jf_limit']);
        $data['chufa_address'] = I('post.chufa_address');
        $data['chufa_date'] = I('post.chufa_date');
        $data['create_time']= time();
        $data['order_remarks'] = I('post.order_remarks');
        $data['order_type'] = I('post.order_type');
        $data['yunfei'] = $yunfei;

        $info = $goods_orders->add($data);



        if(!$info){
            $this->error('订单生成失败',U('Cart/goods_cart'));
			exit;
        }

        //dump($data);
        //exit;

		///////////////////////扣除积分
		$usermodel->where(array('id'=>session('user_id')))->setDec('add_jf_currency',$data['use_jf_currency']);
		$usermodel->where(array('id'=>session('user_id')))->setDec('add_jf_limit',$data['use_jf_limit']);
		$usermodel->where(array('id'=>session('user_id')))->setDec('integral',$data['use_jf_currency']+$data['use_jf_limit']);
		////////////////////////
        $goods_orders_id =  $goods_orders->getLastInsID();
        $map = array();
        foreach($_POST['id'] as $k=>$v){
            $map[$k]['goods_id'] = $_POST['id'][$k];
            $map[$k]['pic_url'] = $_POST['pic_url'][$k];
            $map[$k]['goods_title'] = $_POST['goods_title'][$k];
            $map[$k]['price_new'] = $_POST['price_new'][$k];
            $map[$k]['goods_num'] = $_POST['goods_num'][$k];

            $map[$k]['goods_num_et'] = empty($_POST['goods_num_et'][$k])?0:$_POST['goods_num_et'][$k];

            $map[$k]['chufa_price'] = empty($_POST['chufa_price'][$k])?0:$_POST['chufa_price'][$k];
            $map[$k]['chufa_price_et'] = empty($_POST['chufa_price_et'][$k])?0:$_POST['chufa_price_et'][$k];

            $map[$k]['goods_orders_id'] = $goods_orders_id;
            $map[$k]['user_id'] = session('user_id');
            $map[$k]['taocan_name'] = $_POST['taocan_name'][$k];
            $map[$k]['fanli_jifen'] = $_POST['fanli_jifen'][$k];
            $map[$k]['chufa_date'] = $_POST['chufa_date'][$k];
            $map[$k]['chufa_address'] = $_POST['chufa_address'][$k];
        }

        $goods_orders_record  = M('Goods_orders_record');
        $info =  $goods_orders_record->addAll($map);

		//计算返利积分
		$fanli_jf=0;
		$goods=M('goods');
		$good_ids=$goods_orders_record->field('goods_id,goods_num')->where(array('goods_orders_id'=>$goods_orders_id))->select();
		foreach($good_ids as $k=>$v){
			$jf=$goods->where(array('id'=>$v['goods_id']))->getField('fanli_jifen');
			$jf_sum=$jf*$v['goods_num'];
			$fanli_jf+=$jf_sum;
			$jf=0;
		}
		$goods_orders->where(array('id'=>$goods_orders_id))->save(array('fanli_jifen'=>$fanli_jf));
	
		
		
        if(!$info){
            $this->error('订单生成失败',U('Cart/goods_cart'));
        }
		//这个位置开始进行行程订单后的支付操作（传递商户订单号，商品名称，付款金额，商品描述）
        $orders_num = session('orders_number');
		/*$this->redirect('make_pay_button',array(
            'orders_num'=>$orders_num
        ));*/
         if($_POST['pay_style']==1){
            $this->redirect('make_pay_button',array(
                'orders_num'=>$orders_num
            ));
        }else{
            session('orders_num',$orders_num);
            $this->redirect('Mobile/Wxpay/native_pays');
        }
        
		
    }
	
	/*下单成功后的页面*/
    public  function make_pay_button(){
        require_once("./alipay/alipay.config.php");
        require_once("./alipay/lib/alipay_submit.class.php");

        /**************************请求参数**************************/
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = I('get.orders_num');
        $status=substr($out_trade_no,0,3);
        if($status=='cgw'){
            //订单名称，必填
            $subject = I('get.orders_num');
            $incomeordermodel=M('IncomeOrder');
            $row=$incomeordermodel->where(array('sn'=>$out_trade_no))->find();
            //付款金额，必填
            $total_fee =$row['total']; 
            //$total_fee =0.01;
            //商品描述，可空
            $body = '';
        }else{
            //订单名称，必填
            $subject = I('get.orders_num');
            /* $goods_orders = M('Goods_orders');
             $res = $goods_orders->field('price_sum')->where('orders_num='.$subject)->find();
             //付款金额，必填
             $total_fee = $res['price_sum'];*/
            //这个位置要更具订单号判断到底是商品旅游支付 还是会员充值

            $info_a = strpos($out_trade_no,'u');

            if($info_a==1){
                $info = M('User_huifei')->field('hf_money')->where(array(
                    'orders_num'=>$out_trade_no
                ))->find();
                $price_sum = $info['hf_money'];
            }else{
                $goods_orders = M('Goods_orders');
                $info = $goods_orders->field('price_sum')->where(array(
                    'orders_num'=>$out_trade_no
                ))->find();
                $price_sum = $info['price_sum'];
            }


            //付款金额，必填
            $total_fee =$price_sum;
            // $total_fee =0.01;
            //商品描述，可空
            $body = '';
        }


        /************************************************************/
//构造要请求的参数数组，无需改动
        $parameter = array(
            "service"       => $alipay_config['service'],
            "partner"       => $alipay_config['partner'],
            "seller_id"  => $alipay_config['seller_id'],
            "payment_type"	=> $alipay_config['payment_type'],
            "notify_url"	=> $alipay_config['notify_url'],
            "return_url"	=> $alipay_config['return_url'],

            "anti_phishing_key"=>$alipay_config['anti_phishing_key'],
            "exter_invoke_ip"=>$alipay_config['exter_invoke_ip'],
            "out_trade_no"	=> $out_trade_no,
            "subject"	=> $subject,
            "total_fee"	=> $total_fee,
            "body"	=> $body,
            "_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
            //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.kiX33I&treeId=62&articleId=103740&docType=1
            //如"参数名"=>"参数值"

        );
//建立请求
        $alipaySubmit = new \AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
        echo $html_text;

    }
/*服务器异步通知页面路径 */
    public function pay_responsed(){
        require_once("./alipay/alipay.config.php");
        require_once("./alipay/lib/alipay_notify.class.php");

//计算得出通知验证结果
        $alipayNotify = new \AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();

        if($verify_result) {//验证成功
            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];

            //支付宝交易号
            $trade_no = $_POST['trade_no'];

            //交易状态
            $trade_status = $_POST['trade_status'];

            if($_POST['trade_status'] == 'TRADE_FINISHED') {

            }else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                $status=substr($out_trade_no,0,3);
                if($status=='cgw'){
                    $incomeordermodel=M('IncomeOrder');
                    $row=$incomeordermodel->where(array('sn'=>$out_trade_no))->save(array('status'=>1));

                }else{

                //进行自己的数据库的状态的修改
                /*$data = array();
                $data['pay_status'] = 1;
                $data['pay_time'] = time();
                M('Goods_orders')->where('orders_num='.$out_trade_no)->save($data);*/
                $orders_num =$out_trade_no;
                $info_a = strpos($orders_num,'u');
                if($info_a==1){
                    $data = array();
                    $data['pay_status'] =1;
                    $data['pay_time'] = time();
                    $user_huifei = M('User_huifei');
                    $user_huifei->where(array('orders_num'=>$orders_num))->save($data);
                    $user_huifei->where(array('orders_num'=>$orders_num))->setInc('use_times',1);
                    $res = $user_huifei->field('user_id,hf_money,use_times')->where(array(
                        'orders_num'=>$orders_num
                    ))->find();
                    $user_id = $res['user_id'];
                    $huifei_sum = $res['hf_money'];
                    /************/
                    $admin=M('admin','vip_');
                    $user=M('user');
                    $my=$user->where(array('id'=>$user_id))->find();
                    $arr['account']=$my['mobile'];
                    $arr['password']=$my['password'];
                    $arr['create_time']=NOW_TIME;
                    $arr['status']=1;
                    $admin_id=$admin->add($arr);
                    $auth_group_access=M('auth_group_access','vip_');
                    $auth_group_access->add(array('uid'=>$admin_id,'group_id'=>51));
                    $user->where(array('id'=>$user_id))->save(array('admin_id'=>$admin_id));
                    $map = array();
                    $year=date("Y",NOW_TIME);
                    $month=date("m",NOW_TIME);
                    if($res['use_times']==1){
                        if($huifei_sum==365){
                            $map['grade_name'] ='会员';
//                             R('Award/vipLogic',array($user_id,$year,$month));//取消分成
                            $map['vip_end'] =NOW_TIME-0+31536000;
                        }else if($huifei_sum==30000){
//                             R('Award/sVipLogic',array($user_id,array($year,$month)));
                            $map['grade_name'] ='合伙人';
                        }
                        $map['admin_id'] =$admin_id;
                        $map['status'] =1;
                        $m = M('member','vip_');
                        $m->where(array('user_id'=>$user_id))->save($map);
                    }
                    $this->send_sms($my['mobile']);

                    /*************/
                }else{
                    $data = array();
                    $data['pay_status'] = 1;
                    $data['pay_time'] = time();
                    M('Goods_orders')->where(array(
                        'orders_num'=>$orders_num
                    ))->save($data);
                }

                }


            }



            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

            echo "success";		//请不要修改或删除
        }
        else {
            //验证失败
            echo "fail";
        }
    }
       

    /*
     *页面跳转同步通知页面路径
     * 支付宝支付成功后跳到那个页面
     */
    public function pay_success_to(){
		 if($this->isMobile()==false){
           $this->display();
        }else{
			  $this->redirect('Mobile/Index/index');
		}
        
    }
//>>>判断是电脑还是手机
    function isMobile() {
        $mobile = array();
        static $mobilebrowser_list ='Mobile|iPhone|Android|WAP|NetFront|JAVA|OperasMini|UCWEB|WindowssCE|Symbian|Series|webOS|SonyEricsson|Sony|BlackBerry|Cellphone|dopod|Nokia|samsung|PalmSource|Xphone|Xda|Smartphone|PIEPlus|MEIZU|MIDP|CLDC';
    if(preg_match("/$mobilebrowser_list/i", $_SERVER['HTTP_USER_AGENT'], $mobile)) {
        return true;
    }else{
        if(preg_match('/(mozilla|chrome|safari|opera|m3gate|winwap|openwave)/i', $_SERVER['HTTP_USER_AGENT'])) {
            return false;
        }else{
            if($_GET['mobile'] === 'yes') {
                return true;
            }else{
                return false;
            }
        }
    }
}

    public static function send_sms($mobile){//短信验证码
        header("Content-Type: text/html; charset=UTF-8");
        $flag = 0;
        $params='';//要post的数据
        $verify = rand(100000, 999999);//获取随机验证码
        //以下信息自己填以下
        $argv = array(
                'name'=>'dxwzzy',     //必填参数。用户账号
                'pwd'=>'2E80700AF2D325872D9E11726763',     //必填参数。（web平台：基本资料中的接口密码）
                'content'=>'短信验证码为：'.$verify,   //必填参数。发送内容（1-500 个汉字）UTF-8编码
                'mobile'=>$mobile,   //必填参数。手机号码。多个以英文逗号隔开
                'stime'=>'',   //可选参数。发送时间，填写时已填写的时间发送，不填时为当前时间发送
                'sign'=>'【掌中游】',    //必填参数。用户签名。
                'type'=>'pt',  //必填参数。固定值 pt
                'extno'=>''    //可选参数，扩展码，用户定义扩展码，只能为数字
        );
        foreach ($argv as $key=>$value) {
            if ($flag != 0) {
                $params .= "&";
                $flag = 1;
            }
            $params.= $key."="; $params.= urlencode($value);// urlencode($value);
            $flag = 1;
        }
        $url = "http://web.duanxinwang.cc/asmx/smsservice.aspx?".$params; //提交的url地址
        //echo $url;
        file_get_contents($url);  //获取信息发送后的状态
        return true;
    }
	
	
	//收藏商品
	public function shoucang_add(){
		$m = M('goods_shoucang');
		$where['goods_id'] = $_POST['goods_id'];
		$where['user_id'] = $_SESSION['user_id'];
		$result = $m->where($where)->find();
		if(!empty($result)){
			$this->ajaxReturn(false);
		}
		$_POST['user_id'] = $_SESSION['user_id'];
		$_POST['create_time'] = time();
		$res = $m->add($_POST);
		if($res){
			$this->ajaxReturn(true);
		}else{
			$this->ajaxReturn(false);
		}
	}

	
	//结算
	public function goods_jiesuan(){
		if(empty($_COOKIE['user_id'])){
			$this->redirect('User/user_login');
		}
		include 'area_code.php';
		$goods = M('goods');
		//直接购买
		if($_POST['now_buy'] == 1){
			$price_sum = $_POST['goods_num'] * $_POST['price_new'];
			$goods_data[] = $_POST;			
		}else{
			//购物车中购买，过滤提交的数据
			foreach ($_POST['hidden_xuanze'] as $k=>$v){
				if($v == 1){	//过滤选中的商品ID
					$goods_data[$k]['goods_id'] = $_POST['goods_id'][$k];	//商品ID
					$goods_data[$k]['goods_num'] = $_POST['goods_num'][$k];	//商品数量
					$goods_data[$k]['pic_url'] = $_POST['pic_url'][$k];	//商品图片
					$goods_data[$k]['goods_title'] = $_POST['goods_title'][$k];	//商品图片
					$goods_data[$k]['price_new'] = $_POST['price_new'];  	//商品的单价
					$goods_result = $goods->field('price_new')->where('id='.$_POST['goods_id'][$k])->find();
					$goods_data[$k]['price_new'] = $goods_result['price_new'];	//商品图片
					$goods_data[$k]['price_xiaoji'] = $goods_result['price_new'] * $_POST['goods_num'][$k];	//商品图片
					$price_arr[] = $goods_data[$k]['price_xiaoji'];
				}
			}
			$price_sum = array_sum($price_arr);		//计算价格之和			
		}

		if(!empty($goods_data)){
			$_SESSION['price_sum'] = $price_sum;
			$_SESSION['goods_data'] = $goods_data;	//选中的商品数据临时存储在session中
		}
		$this->assign('price_sum',$_SESSION['price_sum']);	//合计金额
		$this->assign('goods_data',$_SESSION['goods_data']);	//选择的商品
		
		
		//获取默认地址
		$user_address = M('user_address');
		$where['user_id'] = $_COOKIE['user_id'];
		if(empty($_GET['address_id'])){
			$where['status'] = 1;				
		}else{
			$where['id'] = $_GET['address_id'];
		}
		$result_address = $user_address->where($where)->find();
		$result_address['province'] = $arrMArea[$result_address['province']];
		$result_address['city'] = $arrMArea[$result_address['city']];
		$result_address['area'] = $arrMArea[$result_address['area']];
		$this->assign('result_address',$result_address);
		
		
		//优惠券
		$coupons = M('user_coupons');	    	
    	if(!empty($_GET['coupons_id'])){
    		//重新选择优惠券
    		$where_choose['id'] = $_GET['coupons_id'];
    		$result_coupons = $coupons->where($where_choose)->find();
    	}else{
			//查询用户的优惠券			
			$where_coupons['mobile'] = $_COOKIE['mobile'];	//用户手机号
			$where_coupons['use_status'] = array('eq',0);		//查找未使用的
			
			$where_coupons['begin_date'] = array('lt',date('Y-m-d',time()));	//开始时间小于当前时间
			$where_coupons['end_date'] = array('gt',date('Y-m-d',time()));	//结束时间大于当前时间
			$result_coupons = $coupons->where($where_coupons)->order('end_date ASC')->find();		//按照优先使用快过期的	
		}
		//优惠券限制金额，面额都小于总金额才可以使用
		if($result_coupons['money_youhui'] < $_SESSION['price_sum'] && $result_coupons['money_xianzhi'] < $_SESSION['price_sum']){
			$this->assign('result_coupons',$result_coupons);
		}else{
			$result_coupons['id'] = '';
			$result_coupons['money_youhui'] = 0;
		}
		$price_shiji = $_SESSION['price_sum'] - $result_coupons['money_youhui'];	//实际金额   = 总计金额 - 优惠券金额
		$this->assign('price_shiji',$price_shiji);	//实际金额
		
		$this->display();
	}
}